package com.ylkj.patientdrug.ui.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TypefaceSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocation;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.AllStringConstants;
import com.examination.mlib.constants.ClickApi;
import com.examination.mlib.constants.KitArouterConstants;
import com.examination.mlib.manager.PermissionManager;
import com.examination.mlib.utils.LocationUtils;
import com.google.gson.Gson;
import com.examination.mlib.baseold.ModuleBaseFragment;
import com.examination.mlib.interfaceapi.DrugListBackApi;
import com.examination.mlib.interfaceapi.MainCallBack;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.ScreenUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yilijk.base.utils.ToastUtils;
import com.ylkj.patientdrug.entity.CartBatchSaveEntity;
import com.ylkj.patientdrug.entity.CartConfirmAddEntity;
import com.examination.mlib.bean.DefaultEntity;
import com.ylkj.patientdrug.entity.DrugEntity;
import com.ylkj.patientdrug.entity.HomeDrugEntity;
import com.ylkj.patientdrug.entity.InventoryQuantityEntity;
import com.ylkj.patientdrug.entity.MessageEvent;
import com.ylkj.patientdrug.R;
import com.ylkj.patientdrug.adapter.DrugAdapter;
import com.ylkj.patientdrug.entity.MyDoctorListEntity;
import com.ylkj.patientdrug.entity.NearestAddressBean;
import com.ylkj.patientdrug.entity.O2oCartVOSEntity;
import com.ylkj.patientdrug.entity.ResultEntity;
import com.ylkj.patientdrug.entity.ToO2oPayCartDrugEntity;
import com.ylkj.patientdrug.entity.ValidateEntity;
import com.ylkj.patientdrug.entity.ViewEntity;
import com.ylkj.patientdrug.utils.DrugListUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import crossoverone.statuslib.StatusUtil;

import static android.graphics.Typeface.DEFAULT_BOLD;
import static com.examination.mlib.constants.ARouterConstants.DrugListModuleImpl;
import static com.examination.mlib.constants.AllStringConstants.*;
import static com.examination.mlib.constants.ProjectConfigure.Open.isOpenGroup;

@Route(path = ARouterConstants.CART_FRAGMENT)
public class DruglistFragment extends ModuleBaseFragment implements View.OnClickListener {

    private LinearLayout nodataLayout, addressLayout;
    private TextView askHomeTv, addressTv;
    private TextView allGoodsNum, totalAmountTv;
    private LinearLayout bottomLayout;
    private ImageView drug_all_choice;
    private View tempView, checkView;
    private TextView reserve;
    private TextView drugDelete;
    private TextView manageTv;
    private RecyclerView drugRv;
    private DrugAdapter drugAdapter;
    //全选的状态
    private boolean isAllChoiceFlag;
    /**
     * 控制管理完成按钮的状态
     * true是完成（此时为购物车编辑形态）  false是管理（此时为购物车普通形态）
     */
    private boolean manageBtnFlag;
    private List<DrugEntity> drugEntityList = new ArrayList<>();
    public static int width;
    public static ViewEntity viewEntity;
    private int scene = 3;
    private HomeDrugEntity homeDrugEntity;
    //    private double totalAmount;
    private FrameLayout contentFl;
    private LinearLayout amountLl;
    private Dialog limitDialog;
    private boolean isHasO2oDrugs = false;
    private TextView druglist_title;
    private TextView totalReduceAmountTv;


    /**
     * 用于记录当前已勾选的普通商品
     */
    private List<DrugEntity.CommodityListBean> selectDrugBeanList = new ArrayList<>();
    /**
     * 用于记录当前已勾选的O2O商品
     */
    private List<DrugEntity.CommodityListBean> selectO2oBeanList = new ArrayList<>();

    @Override
    public int bondLayout() {
        return R.layout.fragment_druglist;
    }

    @Override
    public void initView() {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", "药品清单载入");
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        ClickUtils.sendEvent("pages_cart_load", getContext(), jsonObject);

        //注册事件
        EventBus.getDefault().register(this);
        nodataLayout = findViewById(R.id.nodata_layout);
        addressLayout = findViewById(R.id.address_layout);
        allGoodsNum = findViewById(R.id.all_goods_num);
        totalReduceAmountTv = findViewById(R.id.tv_totalReduceAmount);
        totalAmountTv = findViewById(R.id.totalAmount);
        askHomeTv = findViewById(R.id.ask_home_tv);
        bottomLayout = findViewById(R.id.bottom_layout);
        manageTv = findViewById(R.id.manage_tv);
        reserve = findViewById(R.id.reserve);
        drugDelete = findViewById(R.id.drug_delete);
        drug_all_choice = findViewById(R.id.drug_all_choice);
        tempView = findViewById(R.id.view_temp);
        checkView = findViewById(R.id.view_check);
        drugRv = findViewById(R.id.drug_list);
        addressTv = findViewById(R.id.address_tv);
        amountLl = findViewById(R.id.ll_amount);
        druglist_title = findViewById(R.id.druglist_title);

        int statusH = StatusUtil.getStatusBarHeight(getContext());
        if (statusH <= 0) {
            statusH = ScreenUtils.dip2px(getContext(), 26);
        }
        druglist_title.setPadding(0, statusH + ScreenUtils.dip2px(getContext(), 20), 0, ScreenUtils.dip2px(getContext(), 20));

        //咨询医生开药
        askHomeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RequestParams jsonObject = new RequestParams();
                jsonObject.put("pageId", 1);
                jsonObject.put("size", 2);
                LoadingUtils.getLoadingUtils(getActivity()).showLoading();
                HttpUtils.get(myDoctorList, jsonObject, new HttpCallBack<MyDoctorListEntity>() {
                    @Override
                    public void onSuccess(MyDoctorListEntity entity, int i) {
                        if (entity.getStatus().equals("200")) {
                            if (entity.getData() != null && entity.getData().getList() != null &&
                                    entity.getData().getList().size() == 1) {
                                Bundle bundle = new Bundle();
                                bundle.putString("doctorId", entity.getData().getList().get(0).getDoctorId());
                                bundle.putInt("selectIndex", 1);
                                DrugListUtils.push(getContext(), KitArouterConstants.IM_DOCTORBUNDLE, KitArouterConstants.Message.DoctorStudio, bundle);
                            } else {

                                DrugListBackApi drugListBackApi = (DrugListBackApi) ARouter.getInstance().build(ARouterConstants.DrugListModuleImpl).navigation();
                                drugListBackApi.changeHomeFragment(getActivity());
                            }
                        } else {
                            DrugListBackApi drugListBackApi = (DrugListBackApi) ARouter.getInstance().build(ARouterConstants.DrugListModuleImpl).navigation();
                            drugListBackApi.changeHomeFragment(getActivity());
                        }
                        LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                    }

                    @Override
                    public void onFailure(String s, int i) {
                        LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                        DrugListBackApi drugListBackApi = (DrugListBackApi) ARouter.getInstance().build(ARouterConstants.DrugListModuleImpl).navigation();
                        drugListBackApi.changeHomeFragment(getActivity());
                    }
                });
            }
        });
        width = getActivity().getWindowManager().getDefaultDisplay().getWidth();


        contentFl = findViewById(R.id.fl_content);
        contentFl.setFocusable(true);
        contentFl.setFocusableInTouchMode(true);


        drugAdapter = new DrugAdapter(drugEntityList);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setInitialPrefetchItemCount(4);
        drugRv.setLayoutManager(manager);
        drugRv.setAdapter(drugAdapter);

    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    //监听软键盘是否显示或隐藏
    private final ViewTreeObserver.OnGlobalLayoutListener contentLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Rect r = new Rect();
            contentFl.getWindowVisibleDisplayFrame(r);
            int screenHeight = contentFl.getRootView().getHeight();
            int heightDifference = screenHeight - (r.bottom);
            if (heightDifference > 200) {
                //软键盘显示
            } else {
                //软键盘隐藏
                contentFl.requestFocus();
                contentFl.requestFocusFromTouch();

            }
        }
    };

    @Override
    public void initData() {
        if (LocationUtils.getInstance().getWhCityBean() != null && !TextUtils.isEmpty(LocationUtils.getInstance().getWhCityBean().getDetailAddress())) {
            addressTv.setText(LocationUtils.getInstance().getWhCityBean().getDetailAddress());
            getDrugList();
        } else {
            getLocationDefault();
        }
    }

    /**
     * 刷新购物车时是否展示loading
     */
    private boolean isShowRefreshLoading = true;

    /**
     * 药品列表
     */
    void getDrugList() {


        manageBtnFlag = false;
        manageTv.setText("管理");
        tempView.setVisibility(View.VISIBLE);
        checkView.setVisibility(View.GONE);
        drugDelete.setTextColor(getResources().getColor(R.color.color_b3));
        reserve.setVisibility(View.VISIBLE);
        drugDelete.setVisibility(View.GONE);
        amountLl.setVisibility(View.VISIBLE);
//        drugEntityList.clear();
        RequestParams paramsJSON = new RequestParams();
        DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
        AMapLocation aMapLocation = LocationUtils.getInstance().getaMapLocation();
        if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
            paramsJSON.put("whCity", whCityBean.getProvinceName() + "," + whCityBean.getCityName());
            paramsJSON.put("lat", whCityBean.getLat());
            paramsJSON.put("lng", whCityBean.getLng());
        } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
            paramsJSON.put("whCity", aMapLocation.getProvince() + "," + aMapLocation.getCity());
            paramsJSON.put("lat", aMapLocation.getLatitude());
            paramsJSON.put("lng", aMapLocation.getLongitude());
        }
        paramsJSON.put("scene", scene);
        if (isShowRefreshLoading) {
            LoadingUtils.getLoadingUtils(getActivity()).showLoading();
        } else {
            isShowRefreshLoading = true;
        }
        HttpUtils.post(cartList, paramsJSON, new HttpCallBack<HomeDrugEntity>() {
            @Override
            public void onSuccess(HomeDrugEntity homeDrugEntity, int i) {
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                DruglistFragment.this.homeDrugEntity = homeDrugEntity;
                if ("200".equals(homeDrugEntity.getCode())) {
                    int totalNum = 0;
                    drugEntityList.clear();
                    if ((homeDrugEntity.getData().getList() != null && homeDrugEntity.getData().getList().size() > 0)) {
                        drugEntityList.addAll(homeDrugEntity.getData().getList());
                        for (DrugEntity entity : homeDrugEntity.getData().getList()) {
                            totalNum += entity.getCommodityList().size();
                        }
                    }
                    if ((homeDrugEntity.getData().getO2oCartVOS() != null && homeDrugEntity.getData().getO2oCartVOS().size() > 0)) {
                        isHasO2oDrugs = true;
                        drugEntityList.addAll(homeDrugEntity.getData().getO2oCartVOS());
                        for (O2oCartVOSEntity entity : homeDrugEntity.getData().getO2oCartVOS()) {
                            totalNum += entity.getCommodityList().size();
                        }
                    } else {
                        isHasO2oDrugs = false;
                    }

//                        totalAmount = 0.0;
                    isAllChoiceFlag = true;
                    selectDrugBeanList.clear();
                    selectO2oBeanList.clear();

                    if (drugEntityList.size() > 0) {
                        for (DrugEntity drugEntity : drugEntityList) {
                            boolean isAllChecked = true;
                            if (drugEntity.getCommodityList() != null && drugEntity.getCommodityList().size() > 0) {
                                for (DrugEntity.CommodityListBean bean : drugEntity.getCommodityList()) {
                                    if (!bean.isChecked()) {
                                        isAllChecked = false;
                                        isAllChoiceFlag = false;
                                    } else {
                                        if (drugEntity.getItemType() == ITEM_TYPE_DRUG) {
                                            selectDrugBeanList.add(bean);
                                        } else if (drugEntity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
                                            selectO2oBeanList.add(bean);
                                        }
//                                            totalAmount += Double.parseDouble(bean.getPrice()) * Integer.parseInt(bean.getAddedQuantity());
                                    }
                                }
                            }
                            drugEntity.setChoice(isAllChecked);
                        }

                        if (isAllChoiceFlag) {
                            drug_all_choice.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.checked));
                        } else {
                            drug_all_choice.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.uncheck));
                        }
                        if (selectDrugBeanList.size() <= 0 && selectO2oBeanList.size() <= 0) {
                            reserve.setBackground(getResources().getDrawable(R.drawable.bg_enable_color));
                        } else {
                            reserve.setBackground(getResources().getDrawable(R.drawable.bg_main_color));
                        }
                        noDataPage(false);
                        allGoodsNum.setText("共" + totalNum + "件商品");
//                            totalAmountTv.setText("¥" + homeDrugEntity.getData().getTotalAmount());
//                            totalAmountTv.setText("¥" + String.format("%.2f", totalAmount));
                        totalAmountTv.setText("¥" + homeDrugEntity.getData().getTotalAmountStr());
                        if (!TextUtils.isEmpty(homeDrugEntity.getData().getTotalReduceAmount())) {
                            String totalReduce = homeDrugEntity.getData().getTotalReduceAmount();
                            double totalReduceDouble = 0;
                            try {
                                totalReduceDouble = Double.parseDouble(totalReduce);
                            } catch (Throwable throwable) {

                            }
                            if (totalReduceDouble > 0) {
                                totalReduceAmountTv.setText("不含运费  已减¥" + homeDrugEntity.getData().getTotalReduceAmount());
                            } else {
                                totalReduceAmountTv.setText("不含运费");
                            }
                        } else {
                            totalReduceAmountTv.setText("不含运费");
                        }
//                            drugEntityList = homeDrugEntity.getData().getList();
//                            drugAdapter = new DrugAdapter(R.layout.item_drug, drugEntityList);
                        //
//                            drugAdapter = new DrugAdapter(drugEntityList);
//                            LinearLayoutManager manager = new LinearLayoutManager(getActivity());
//                            manager.setInitialPrefetchItemCount(4);
//                            drugRv.setLayoutManager(manager);
//                            drugRv.setAdapter(drugAdapter);
                        drugAdapter.notifyDataSetChanged();
                    } else {
                        allGoodsNum.setText("共" + totalNum + "件商品");
                        totalReduceAmountTv.setText("不含运费");
                        noDataPage(true);
                    }
                } else {
                    if (homeDrugEntity != null && !TextUtils.isEmpty(homeDrugEntity.getMsg())) {
                        ToastUtils.showShort(homeDrugEntity.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
            }
        }).setCancelTag(cartList);
    }

    /**
     * 获取默认地址
     */
    void getLocationDefault() {
//        HttpUtils.get(getDefault, new HttpCallBack<DefaultEntity>() {
//            @Override
//            public void onSuccess(DefaultEntity defaultEntity, int i) {
//                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
//                if ("200".equals(defaultEntity.getStatus()) && defaultEntity.getData() != null) {
//                    addressTv.setText(defaultEntity.getData().getDetailAddress());
//                    LocationUtils.getInstance().setWhCityBean(defaultEntity.getData());
//                    DrugListBackApi api = (DrugListBackApi) ARouter.getInstance().build(ARouterConstants.DrugListModuleImpl).navigation();
//                    HashMap<String, String> map = api.getTemporaryDataStorage();
//                    getDrugList();
//                    return;
//                } else {
//                    getLocation();
//                }
//            }
//
//            @Override
//            public void onFailure(String s, int i) {
//                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
//                getDrugList();
//            }
//        });

        LoadingUtils.getLoadingUtils(getActivity()).showLoading();
        DrugListUtils.getLocalAddress(new MainCallBack() {
            @Override
            public void onSuccess(AMapLocation aMapLocation) {

                double latitude = aMapLocation.getLatitude();
                double longitude = aMapLocation.getLongitude();
                RequestParams params = new RequestParams();
                params.put("lat", latitude);
                params.put("lng", longitude);

                HttpUtils.post(getNearestAddress, params, new HttpCallBack<NearestAddressBean>() {
                    @Override
                    public void onSuccess(NearestAddressBean s, int i) {
                        if (s.isResult()) {
                            if (s.getData() != null && !TextUtils.isEmpty(s.getData().getAddressId())) {
                                addressTv.setText(s.getData().getDetailAddress());
                                DefaultEntity.DataBean dataBean = new DefaultEntity.DataBean();
                                dataBean.setAddressId(s.getData().getAddressId());
                                dataBean.setName(s.getData().getName());
                                dataBean.setProvinceName(s.getData().getProvinceName());
                                dataBean.setCityName(s.getData().getCityName());
                                dataBean.setCountyName(s.getData().getCountyName());
                                dataBean.setProvinceName(s.getData().getProvinceName());
                                dataBean.setTelephone(s.getData().getTelephone());
                                dataBean.setDetailAddress(s.getData().getDetailAddress());
                                dataBean.setDefaultAddress(s.getData().isDefaultAddress());
                                dataBean.setLat(s.getData().getLat());
                                dataBean.setLng(s.getData().getLng());
                                LocationUtils.getInstance().setWhCityBean(dataBean);
                                DrugListBackApi api = (DrugListBackApi) ARouter.getInstance().build(ARouterConstants.DrugListModuleImpl).navigation();
                                HashMap<String, String> map = api.getTemporaryDataStorage();
                                getDrugList();
                            } else {
                                LocationUtils.getInstance().setaMapLocation(aMapLocation);
                                String address = aMapLocation.getAddress();
                                String district = aMapLocation.getDistrict();
                                if (!TextUtils.isEmpty(address) && !TextUtils.isEmpty(district) && address.contains(district)) {
                                    address = address.replaceFirst(district, "");
                                }
                                addressTv.setText(address);
                            }
                        } else {
                            LocationUtils.getInstance().setaMapLocation(aMapLocation);
                            String address = aMapLocation.getAddress();
                            String district = aMapLocation.getDistrict();
                            if (!TextUtils.isEmpty(address) && !TextUtils.isEmpty(district) && address.contains(district)) {
                                address = address.replaceFirst(district, "");
                            }
                            addressTv.setText(address);
                        }
                        getDrugList();
                    }

                    @Override
                    public void onFailure(String s, int i) {
                        LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                        getDrugList();
                    }
                });
            }

            @Override
            public void onError(String e) {
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                getDrugList();
            }
        });
    }

    /**
     * 获取定位
     */
    void getLocation() {
        String[] premissions = new String[]{
                "android.permission.ACCESS_FINE_LOCATION",
        };
        //判断当前版本号
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String s : premissions) {
                //判断权限授权执行
                if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(getActivity(), s)) {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{s}, 1);
                }
            }
        }
        DrugListUtils.getLocalAddress(new MainCallBack() {
            @Override
            public void onSuccess(AMapLocation location) {
                LocationUtils.getInstance().setaMapLocation(location);
                String address = location.getAddress();
                String district = location.getDistrict();
                if (!TextUtils.isEmpty(address) && !TextUtils.isEmpty(district) && address.contains(district)) {
                    address = address.replaceFirst(district, "");
                }
                addressTv.setText(address);
                getDrugList();
            }

            @Override
            public void onError(String e) {
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                getDrugList();
            }
        });
    }

    /**
     * 显示列表页和空数据页面布局
     *
     * @param isNoData true显示空页面  false显示列表
     */
    void noDataPage(boolean isNoData) {
        if (isNoData) {
            nodataLayout.setVisibility(View.VISIBLE);
            manageTv.setVisibility(View.GONE);
            drugRv.setVisibility(View.GONE);
            bottomLayout.setVisibility(View.GONE);
        } else {
            nodataLayout.setVisibility(View.GONE);
            manageTv.setVisibility(View.VISIBLE);
            drugRv.setVisibility(View.VISIBLE);
            bottomLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void initEvent() {
        drug_all_choice.setOnClickListener(this);
        manageTv.setOnClickListener(this);
        drugDelete.setOnClickListener(this);
        reserve.setOnClickListener(this);
        addressLayout.setOnClickListener(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) throws JSONException {
        if ("allChoice".equals(messageEvent.getMessage())) {
            ClickUtils.sendEvent(ClickApi.CartList.click_all_choice_group, getContext(), "勾选一组药品");

//            new Thread(new Runnable() {
//                @Override
//                public void run() {
            DrugEntity drugEntity = drugEntityList.get(messageEvent.getPosition());
            // 医生的问诊开方下的药品和1小时急送药店购买的药品不可以同时选中
            if (!manageBtnFlag) {
//                if (drugEntity.getItemType() == ITEM_TYPE_DRUG && selectO2oBeanList.size() > 0) {
//                    return;
//                } else if (drugEntity.getItemType() == ITEM_TYPE_O2O_CART_VOS && selectDrugBeanList.size() > 0) {
//                    return;
//                }
            }


            drugEntity.setChoice(messageEvent.isAllChoice());
            for (int i = 0; i < drugEntity.getCommodityList().size(); i++) {
                if (!manageBtnFlag && "1".equals(drugEntity.getCommodityList().get(i).getIsRegular()) && messageEvent.isAllChoice()) {
                    //定期购商品不可选中
                    if (drugEntity.getCommodityList().size() == 1) {
                        ToastUtils.showShort("此商品当前不支持零售");
                    }
                    continue;
                }
                drugEntity.getCommodityList().get(i).setChecked(messageEvent.isAllChoice());
            }
            if (!manageBtnFlag) {
                List<DrugEntity> tempDrugList = new ArrayList<>();
                tempDrugList.add(drugEntity);
                doBatchSave(tempDrugList);
            } else {
                // 管理编辑购物车状态
                boolean isHasChecked = false;
                outer:
                {
                    for (DrugEntity entity : drugEntityList) {
                        for (DrugEntity.CommodityListBean bean : entity.getCommodityList()) {
                            if (bean.isChecked()) {
                                isHasChecked = true;
                                break outer;
                            }
                        }
                    }
                }
                if (isHasChecked) {
                    drugDelete.setTextColor(getResources().getColor(R.color.new_theme));
                } else {
                    drugDelete.setTextColor(getResources().getColor(R.color.color_b3));
                }
            }
            drugAdapter.notifyDataSetChanged();
            boolean isTrue = true;  //判断是不是全选
//            totalAmount = 0.0;
            if (!manageBtnFlag) {
                if (drugEntity.getItemType() == ITEM_TYPE_DRUG) {
                    selectDrugBeanList.clear();
                } else if (drugEntity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
                    selectO2oBeanList.clear();
                }
            }
            for (int i = 0; i < drugEntityList.size(); i++) {
                if (!drugEntityList.get(i).isChoice()) {
                    isTrue = false;
//                    break;
                }
                for (int j = 0; j < drugEntityList.get(i).getCommodityList().size(); j++) {
                    DrugEntity.CommodityListBean bean = drugEntityList.get(i).getCommodityList().get(j);
                    if (!bean.isChecked()) {
                        isTrue = false;
//                        break;
                    } else {
                        if (!manageBtnFlag) {
                            if (drugEntity.getItemType() == ITEM_TYPE_DRUG) {
                                selectDrugBeanList.add(bean);
                            } else if (drugEntity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
                                selectO2oBeanList.add(bean);
                            }
                        }
//                        totalAmount += Double.parseDouble(bean.getPrice()) * Integer.parseInt(bean.getAddedQuantity());
                    }
                }
            }
//            totalAmountTv.setText("¥" + String.format("%.2f", totalAmount));

            if (isTrue) {  //设置全选
                isAllChoiceFlag = true;
                drug_all_choice.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.checked));
            } else {
                isAllChoiceFlag = false;
                drug_all_choice.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.uncheck));
            }
            if (selectDrugBeanList.size() <= 0 && selectO2oBeanList.size() <= 0) {
                reserve.setBackground(getResources().getDrawable(R.drawable.bg_enable_color));
            } else {
                reserve.setBackground(getResources().getDrawable(R.drawable.bg_main_color));
            }
//                }
//            }).start();
        } else if ("childClick".equals(messageEvent.getMessage())) {
            ClickUtils.sendEvent(ClickApi.CartList.click_drug, getContext(), "药品点击");

            Bundle bundle = new Bundle();

            DrugEntity drugEntity = drugEntityList.get(messageEvent.getPosition());
            DrugEntity.CommodityListBean commodityListBean = drugEntity.getCommodityList().get(messageEvent.getChildPosition());

            if (drugEntity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
                O2oCartVOSEntity vosEntity = (O2oCartVOSEntity) drugEntity;
                bundle.putString("storeId", "" + vosEntity.getStoreId());
                bundle.putString("openTime", "" + vosEntity.getOpenTime());
                bundle.putString("businessScope", "" + vosEntity.getBusinessScope());
                bundle.putInt("scene", 2);
            } else {
                bundle.putInt("scene", 1);
            }
            DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
            if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getAddressId() + "")) {
                bundle.putString("addressId", whCityBean.getAddressId() + "");
                bundle.putDouble("latitude", whCityBean.getLat());
                bundle.putDouble("longitude", whCityBean.getLng());
            }

            if ("drug".equals(commodityListBean.getCommodityType())) {
                bundle.putString("id", "" + commodityListBean.getDrugId());
            } else if ("PT".equals(commodityListBean.getCommodityType())) {
                bundle.putString("commodityId", "" + commodityListBean.getCommodityId());
            } else {
                bundle.putString("packetId", "" + commodityListBean.getPacketId());
            }
            bundle.putString("doctorId", commodityListBean.getDoctorId() + "");
            bundle.putString("commodityType", commodityListBean.getCommodityType() + "");
            DrugListUtils.push(getContext(),
                    KitArouterConstants.CART_DOCTORBUNDLE,
                    KitArouterConstants.Cart.DrugDetail,
                    bundle);
        } else if ("childChoice".equals(messageEvent.getMessage())) {
            ClickUtils.sendEvent(ClickApi.CartList.click_drug_choice, getContext(), "勾选药品");

            DrugEntity drugEntity = drugEntityList.get(messageEvent.getPosition());
            DrugEntity.CommodityListBean commodityListBean = drugEntity.getCommodityList().get(messageEvent.getChildPosition());
            // 医生的问诊开方下的药品和1小时急送药店购买的药品不可以同时选中
            if (!manageBtnFlag) {
                if ("1".equals(commodityListBean.getIsRegular()) && messageEvent.isAllChoice()) {
                    //定期购商品不可选中
                    ToastUtils.showShort("此商品当前不支持零售");
                    return;
                }
                if (commodityListBean.isSoldOut() && messageEvent.isAllChoice()) {
//                if (commodityListBean.isSoldOut() && messageEvent.isAllChoice() && drugEntity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
                    ToastUtils.showShort("无货商品不支持勾选");
                    return;
                }
                if (!commodityListBean.isPublished() && messageEvent.isAllChoice()) {
                    ToastUtils.showShort("下架商品不支持勾选");
                    return;
                }

//                if (drugEntity.getItemType() == ITEM_TYPE_DRUG && selectO2oBeanList.size() > 0) {
//                    return;
//                } else if (drugEntity.getItemType() == ITEM_TYPE_O2O_CART_VOS && selectDrugBeanList.size() > 0) {
//                    return;
//                }
            }


            commodityListBean.setChecked(messageEvent.isAllChoice());
            if (!manageBtnFlag) {
                List<DrugEntity> tempList = new ArrayList<>();
                tempList.add(drugEntity);
                doBatchSave(tempList);
            } else {
                // 管理编辑购物车状态
                boolean isHasChecked = false;
                outer:
                {
                    for (DrugEntity entity : drugEntityList) {
                        for (DrugEntity.CommodityListBean bean : entity.getCommodityList()) {
                            if (bean.isChecked()) {
                                isHasChecked = true;
                                break outer;
                            }
                        }
                    }
                }
                if (isHasChecked) {
                    drugDelete.setTextColor(getResources().getColor(R.color.new_theme));
                } else {
                    drugDelete.setTextColor(getResources().getColor(R.color.color_b3));
                }
            }

//            drugEntityList.get(messageEvent.getPosition()).getCommodityList().get(messageEvent.getChildPosition()).setChecked(messageEvent.isAllChoice());
            boolean isAllTrue = true;  //判断是不是全选
//            totalAmount = 0.0;
            if (!manageBtnFlag) {
                if (drugEntity.getItemType() == ITEM_TYPE_DRUG) {
                    selectDrugBeanList.clear();
                } else if (drugEntity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
                    selectO2oBeanList.clear();
                }
            }
            for (int i = 0; i < drugEntityList.size(); i++) {
                boolean isTrue = true;  //判断是不是全选
                for (int j = 0; j < drugEntityList.get(i).getCommodityList().size(); j++) {
                    DrugEntity.CommodityListBean bean = drugEntityList.get(i).getCommodityList().get(j);
                    if (!bean.isChecked()) {
                        isTrue = false;
                        isAllTrue = false;

                    } else {
                        if (!manageBtnFlag) {
                            if (drugEntity.getItemType() == ITEM_TYPE_DRUG) {
                                selectDrugBeanList.add(bean);
                            } else if (drugEntity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
                                selectO2oBeanList.add(bean);
                            }
                        }
//                        totalAmount += Double.parseDouble(bean.getPrice()) * Integer.parseInt(bean.getAddedQuantity());
                    }
                }
                drugEntityList.get(i).setChoice(isTrue);
            }

//            totalAmountTv.setText("¥" + String.format("%.2f", totalAmount));
            drugAdapter.notifyDataSetChanged();
            if (isAllTrue) {  //设置全选
                isAllChoiceFlag = true;
                drug_all_choice.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.checked));
            } else {
                isAllChoiceFlag = false;
                drug_all_choice.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.uncheck));
            }
            if (selectDrugBeanList.size() <= 0 && selectO2oBeanList.size() <= 0) {
                reserve.setBackground(getResources().getDrawable(R.drawable.bg_enable_color));
            } else {
                reserve.setBackground(getResources().getDrawable(R.drawable.bg_main_color));
            }
        } else if ("childQuantityChange".equals(messageEvent.getMessage())) {

            int quantity = messageEvent.getQuantity();
            DrugEntity entity = drugEntityList.get(messageEvent.getPosition());
            DrugEntity.CommodityListBean bean = entity.getCommodityList().get(messageEvent.getChildPosition());
            RequestParams jsonObject = new RequestParams();
            jsonObject.put("commodityType", bean.getCommodityType());
            jsonObject.put("commodityId", bean.getCommodityId());
            DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
            AMapLocation aMapLocation = LocationUtils.getInstance().getaMapLocation();
            if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
                jsonObject.put("whCity", whCityBean.getProvinceName() + "," + whCityBean.getCityName());
                jsonObject.put("lat", whCityBean.getLat() + "");
                jsonObject.put("lng", whCityBean.getLng() + "");
//            if (!TextUtils.isEmpty(whCityBean.getAddressId())) {
//                jsonObject.put("addressId", whCityBean.getAddressId());
//            }
            } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
                jsonObject.put("whCity", aMapLocation.getProvince() + "," + aMapLocation.getCity());
                jsonObject.put("lat", aMapLocation.getLatitude() + "");
                jsonObject.put("lng", aMapLocation.getLongitude() + "");
            }
            if (entity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
                jsonObject.put("storeId", ((O2oCartVOSEntity) entity).getStoreId());
            }
            LoadingUtils.getLoadingUtils(getActivity()).showLoading();
            HttpUtils.post(getInventoryQuantity, jsonObject, new HttpCallBack<InventoryQuantityEntity>() {
                @Override
                public void onSuccess(InventoryQuantityEntity quantityEntity, int i) {
//                    LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                    if (quantityEntity.isResult()) {
                        if (quantityEntity.getData() <= 0) {
//                            Toast.makeText(getContext(), "该商品已无货", Toast.LENGTH_SHORT).show();
                            ToastUtils.showShort("该商品已无货");
                            isShowRefreshLoading = false;
                            initData();
                        } else if (quantity > quantityEntity.getData()) {
//                            Toast.makeText(getContext(), "该商品当前最多可购买" + quantityEntity.getData() + "件", Toast.LENGTH_SHORT).show();
                            ToastUtils.showShort("该商品当前最多可购买" + quantityEntity.getData() + "件");
                            isShowRefreshLoading = false;
//                            initData();
                            try {
                                changQuantity(entity, bean, quantityEntity.getData(), messageEvent.getPosition(), messageEvent.getChildPosition());
                            } catch (JSONException e) {
                                e.printStackTrace();
                                isShowRefreshLoading = false;
                                initData();
                            }
                        } else {
                            try {
                                changQuantity(entity, bean, quantity, messageEvent.getPosition(), messageEvent.getChildPosition());
                            } catch (JSONException e) {
                                e.printStackTrace();
                                isShowRefreshLoading = false;
                                initData();
                            }

                        }
                    } else {
                        if (!TextUtils.isEmpty(quantityEntity.getMsg())) {
//                            Toast.makeText(getContext(), quantityEntity.getMessage(), Toast.LENGTH_SHORT).show();
                            ToastUtils.showShort(quantityEntity.getMsg());
                        }
                        isShowRefreshLoading = false;
                        initData();
                    }
                }

                @Override
                public void onFailure(String s, int i) {
//                    LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                    if (!TextUtils.isEmpty(s)) {
//                        Toast.makeText(getContext(), failureMsg, Toast.LENGTH_SHORT).show();
                        ToastUtils.showShort(s);
                    }
                    isShowRefreshLoading = false;
                    initData();
                }
            });

        } else if ("delete".equals(messageEvent.getMessage())) {
            ClickUtils.sendEvent(ClickApi.CartList.click_slide_delete, getContext(), "左滑删除药品");

            RequestParams jsonObject = new RequestParams();
            JSONArray list = new JSONArray();
            JSONObject submitDeleteData = new JSONObject();
            JSONObject data = new JSONObject();
            data.put("addedQuantity", drugEntityList.get(messageEvent.getPosition()).getCommodityList().get(messageEvent.getChildPosition()).getAddedQuantity());
            data.put("commodityId", drugEntityList.get(messageEvent.getPosition()).getCommodityList().get(messageEvent.getChildPosition()).getCommodityId());
            data.put("commodityType", drugEntityList.get(messageEvent.getPosition()).getCommodityList().get(messageEvent.getChildPosition()).getCommodityType());
            data.put("price", drugEntityList.get(messageEvent.getPosition()).getCommodityList().get(messageEvent.getChildPosition()).getPrice());
            JSONArray jsonArray = new JSONArray();
            jsonArray.put(data);
            submitDeleteData.put("doctorId", drugEntityList.get(messageEvent.getPosition()).getCommodityList().get(messageEvent.getChildPosition()).getDoctorId() + "");
            submitDeleteData.put("commodityList", jsonArray);
            list.put(submitDeleteData);
            jsonObject.put("list", list);
            LoadingUtils.getLoadingUtils(getActivity()).showLoading();
            HttpUtils.post(cartDelete, jsonObject, new HttpCallBack<ResultEntity>() {
                @Override
                public void onSuccess(ResultEntity resultEntity, int i) {
                    if ("200".equals(resultEntity.getCode())) {
//                        drugEntityList.get(messageEvent.getPosition()).getCommodityList().remove(messageEvent.getChildPosition());
//                        if (drugEntityList.get(messageEvent.getPosition()).getCommodityList().size() == 0) {
//                            drugEntityList.remove(messageEvent.getPosition());
//                        }
//                        initData();
//                            if (drugEntityList.size() == 0) {
//                                noDataPage(true);
//                            } else {
//                                drugAdapter.notifyDataSetChanged();
//                            }
//                            Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
                        ToastUtils.showShort("删除成功");
                    } else {
//                            Toast.makeText(getActivity(), resultEntity.getMessage(), Toast.LENGTH_SHORT).show();

                        if (!TextUtils.isEmpty(resultEntity.getMsg())) {
                            ToastUtils.showShort(resultEntity.getMsg());
                        }
                    }
                    isShowRefreshLoading = false;
                    initData();
                }

                @Override
                public void onFailure(String s, int i) {
//                    LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                    isShowRefreshLoading = false;
                    initData();
                }
            });
        }
    }

    private void changQuantity(DrugEntity entity, DrugEntity.CommodityListBean bean, int quantity, int position, int childPosition) throws JSONException {
        if (lock) {
            return;
        }
        lock = true;
        RequestParams jsonObject = new RequestParams();
        jsonObject.put("doctorId", bean.getDoctorId());
        DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
        AMapLocation aMapLocation = LocationUtils.getInstance().getaMapLocation();
        if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
            jsonObject.put("whCity", whCityBean.getProvinceName() + "," + whCityBean.getCityName());
            jsonObject.put("lat", whCityBean.getLat() + "");
            jsonObject.put("lng", whCityBean.getLng() + "");
//            if (!TextUtils.isEmpty(whCityBean.getAddressId())) {
//                jsonObject.put("addressId", whCityBean.getAddressId());
//            }
        } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
            jsonObject.put("whCity", aMapLocation.getProvince() + "," + aMapLocation.getCity());
            jsonObject.put("lat", aMapLocation.getLatitude() + "");
            jsonObject.put("lng", aMapLocation.getLongitude() + "");
        }
        jsonObject.put("commodityId", bean.getCommodityId());
        jsonObject.put("commodityType", bean.getCommodityType());
        jsonObject.put("quantity", quantity);
        jsonObject.put("price", bean.getPrice());
        jsonObject.put("checked", bean.isChecked());
        jsonObject.put("scene", 3);
        if (entity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
            jsonObject.put("storeId", ((O2oCartVOSEntity) entity).getStoreId());
        }
//        LoadingUtils.getLoadingUtils(getActivity()).showLoading();
        HttpUtils.post(cartSave, jsonObject, new HttpCallBack<ResultEntity>() {
            @Override
            public void onSuccess(ResultEntity resultEntity, int i) {
//                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                if ("200".equals(resultEntity.getCode())) {
                    drugEntityList.get(position).getCommodityList().get(childPosition).setAddedQuantity(quantity + "");

//                    totalAmount = 0.0;
                    for (DrugEntity drugEntity : drugEntityList) {
                        boolean isAllChecked = true;
                        if (drugEntity.getCommodityList() != null && drugEntity.getCommodityList().size() > 0) {
                            for (DrugEntity.CommodityListBean bean : drugEntity.getCommodityList()) {
                                if (!bean.isChecked()) {
                                    isAllChecked = false;
                                } else {
                                }
                            }
                        }
                        drugEntity.setChoice(isAllChecked);
                    }
                    drugAdapter.notifyDataSetChanged();
                    isShowRefreshLoading = false;
                    initData();
                    lock = false;
                } else {
                    if (!TextUtils.isEmpty(resultEntity.getMsg())) {
                        ToastUtils.showShort(resultEntity.getMsg());
                    }
                    isShowRefreshLoading = false;
                    initData();
                    lock = false;
                }
            }

            @Override
            public void onFailure(String s, int i) {
                try {
                    ResultEntity entity1 = new Gson().fromJson(s, ResultEntity.class);
                    if (!TextUtils.isEmpty(entity1.getMsg())) {
                        ToastUtils.showShort(entity1.getMsg());
                    }
                } catch (Throwable throwable) {
                    if (!TextUtils.isEmpty(s)) {
                        ToastUtils.showShort(s);
                    }
                }

//                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();

                lock = false;
                isShowRefreshLoading = false;
                initData();

            }
        });
    }

    /**
     * 網絡請求加鎖
     */
    boolean lock = false;

    /**
     * 勾选逻辑
     *
     * @param drugList
     * @throws JSONException
     */
    private void doBatchSave(List<DrugEntity> drugList) throws JSONException {
        RequestParams jsonObject = new RequestParams();
        DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
        AMapLocation aMapLocation = LocationUtils.getInstance().getaMapLocation();
        if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
            jsonObject.put("whCity", whCityBean.getProvinceName() + "," + whCityBean.getCityName());
            jsonObject.put("lat", whCityBean.getLat() + "");
            jsonObject.put("lng", whCityBean.getLng() + "");
//            if (!TextUtils.isEmpty(whCityBean.getAddressId())) {
//                jsonObject.put("addressId", whCityBean.getAddressId());
//            }
        } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
            jsonObject.put("whCity", aMapLocation.getProvince() + "," + aMapLocation.getCity());
            jsonObject.put("lat", aMapLocation.getLatitude() + "");
            jsonObject.put("lng", aMapLocation.getLongitude() + "");
        }
        jsonObject.put("scene", scene);

        JSONArray jsonArray = new JSONArray();
        for (DrugEntity drugEntity : drugList) {
            for (DrugEntity.CommodityListBean bean : drugEntity.getCommodityList()) {
                if ((bean.isSoldOut() || !bean.isPublished()) && bean.isChecked()) {
                    continue;
                }
                JSONObject drug = new JSONObject();
                drug.put("doctorId", bean.getDoctorId());
//                if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
//                    drug.put("whCity", whCityBean.getProvinceName() + "," + whCityBean.getCityName());
//                } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
//                    drug.put("whCity", aMapLocation.getProvince() + "," + aMapLocation.getCity());
//                }
//                if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
//                    drug.put("whCity", whCityBean.getProvinceName() + "," + whCityBean.getCityName());
//                    drug.put("lat", whCityBean.getLat()+"");
//                    drug.put("lng", whCityBean.getLng()+"");
//                    if (!TextUtils.isEmpty(whCityBean.getAddressId())) {
//                        drug.put("addressId", whCityBean.getAddressId());
//                    }
//                } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
//                    drug.put("whCity", aMapLocation.getProvince() + "," + aMapLocation.getCity());
//                    drug.put("lat", aMapLocation.getLatitude()+"");
//                    drug.put("lng", aMapLocation.getLongitude()+"");
//                }
                drug.put("commodityId", bean.getCommodityId());
                drug.put("commodityType", bean.getCommodityType());
                drug.put("quantity", bean.getAddedQuantity());
                drug.put("price", bean.getPrice());
                drug.put("checked", bean.isChecked());
                if (drugEntity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
                    drug.put("storeId", ((O2oCartVOSEntity) drugEntity).getStoreId());
                    drug.put("scene", 2);
                } else {
                    drug.put("scene", 1);
                }
                jsonArray.put(drug);
            }
        }

        if (jsonArray.length() <= 0) {
            isShowRefreshLoading = false;
            initData();
            return;
        }
        jsonObject.put("list", jsonArray);
        LoadingUtils.getLoadingUtils(getActivity()).showLoading();
        HttpUtils.post(cartBatchSave, jsonObject, new HttpCallBack<CartBatchSaveEntity>() {
            @Override
            public void onSuccess(CartBatchSaveEntity cartBatchSaveEntity, int i) {
//                if ("200".equals(cartBatchSaveEntity.getCode())) {
//                }
                if (!TextUtils.isEmpty(cartBatchSaveEntity.getMsg())) {
                    ToastUtils.showShort(cartBatchSaveEntity.getMsg());
                }
                isShowRefreshLoading = false;
                initData();
            }

            @Override
            public void onFailure(String s, int i) {

//                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                try {
                    CartBatchSaveEntity entity1 = new Gson().fromJson(s, CartBatchSaveEntity.class);
                    if (!TextUtils.isEmpty(entity1.getMsg())) {
                        ToastUtils.showShort(entity1.getMsg());
                    }
                } catch (Throwable throwable) {
                    if (!TextUtils.isEmpty(s)) {
                        ToastUtils.showShort(s);
                    }
                }

                isShowRefreshLoading = false;
                initData();
            }
        });

    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.manage_tv) {
            if (manageBtnFlag) {
                ClickUtils.sendEvent(ClickApi.CartList.click_manage_complete, getContext(), "药品清单管理完成点击");
                manageBtnFlag = false;
                manageTv.setText("管理");
                tempView.setVisibility(View.VISIBLE);
                checkView.setVisibility(View.GONE);
                drugDelete.setTextColor(getResources().getColor(R.color.color_b3));
                initData();
                amountLl.setVisibility(View.VISIBLE);
                reserve.setVisibility(View.VISIBLE);
                drugDelete.setVisibility(View.GONE);
            } else {
                ClickUtils.sendEvent(ClickApi.CartList.click_manage, getContext(), "药品清单管理点击");
                manageTv.setText("完成");
                tempView.setVisibility(View.GONE);
                checkView.setVisibility(View.VISIBLE);
                drugDelete.setTextColor(getResources().getColor(R.color.color_b3));
                manageBtnFlag = true;
                amountLl.setVisibility(View.INVISIBLE);
                reserve.setVisibility(View.GONE);
                drugDelete.setVisibility(View.VISIBLE);
                for (DrugEntity entity : drugEntityList) {
                    for (DrugEntity.CommodityListBean bean : entity.getCommodityList()) {
                        bean.setChecked(false);
                    }
                    entity.setChoice(false);
                }
                isAllChoiceFlag = false;
                drug_all_choice.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.uncheck));
//                setAllChoice(false);
                drugAdapter.notifyDataSetChanged();
            }
        } else if (view.getId() == R.id.reserve) {
            ClickUtils.sendEvent(ClickApi.CartList.click_reserve, getContext(), "立即预定点击");

            boolean hasSoldOut = false;
            double totalAmount = 0.0;
            List<DrugEntity> selectEntityList = new ArrayList<>();
            List<O2oCartVOSEntity> selectO2oEntityList = new ArrayList<>();
            for (DrugEntity entity : drugEntityList) {
                if (entity.getItemType() == ITEM_TYPE_DRUG) {
                    List<DrugEntity.CommodityListBean> beans = new ArrayList<>();
                    for (DrugEntity.CommodityListBean bean : entity.getCommodityList()) {
                        if (bean.isChecked()) {
                            beans.add(bean);
                            totalAmount += Double.parseDouble(bean.getPrice()) * Integer.parseInt(bean.getAddedQuantity());
                            if (bean.isSoldOut() || !bean.isPublished()) {
                                hasSoldOut = true;
                            }
                        }
                    }
                    if (beans.size() > 0) {
                        DrugEntity entity1 = new DrugEntity();
                        entity1.setDoctorId(entity.getDoctorId());
                        entity1.setCommodityList(beans);
                        selectEntityList.add(entity1);
                    }

                } else if (entity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
                    O2oCartVOSEntity vosEntity = (O2oCartVOSEntity) entity;
                    List<O2oCartVOSEntity.CommodityListBean> beans = new ArrayList<>();
                    for (O2oCartVOSEntity.CommodityListBean bean : vosEntity.getCommodityList()) {
                        if (bean.isChecked()) {
                            beans.add(bean);
                            totalAmount += Double.parseDouble(bean.getPrice()) * Integer.parseInt(bean.getAddedQuantity());
                            if (bean.isSoldOut() || !bean.isPublished()) {
                                hasSoldOut = true;
                            }
                        }
                    }
                    if (beans.size() > 0) {
                        O2oCartVOSEntity entity1 = new O2oCartVOSEntity();
                        entity1.setDoctorId(beans.get(0).getDoctorId());
                        entity1.setStoreId(((O2oCartVOSEntity) entity).getStoreId());
                        entity1.setCommodityList(beans);
                        selectO2oEntityList.add(entity1);
                    }

                }
            }

            if (hasSoldOut && selectO2oEntityList.size() > 0 && selectO2oEntityList.get(0).getCommodityList().size() > 0) {
//                Toast.makeText(getContext(), "您选中的部分商品暂时无货或库存不足", Toast.LENGTH_SHORT).show();
                ToastUtils.showShort("您选中的部分商品暂时无货或库存不足");
                return;
            }
            if (selectEntityList.size() <= 0 && selectO2oEntityList.size() <= 0) {
//                Toast.makeText(getContext(), "请选择药品", Toast.LENGTH_SHORT).show();
                ToastUtils.showShort("请选择药品");
                return;
            }

            RequestParams jsonObject = new RequestParams();
            RequestParams validateParams = new RequestParams();
            try {
                DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
                AMapLocation aMapLocation = LocationUtils.getInstance().getaMapLocation();
                if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
                    jsonObject.put("whCity", whCityBean.getProvinceName() + "," + whCityBean.getCityName());
                    jsonObject.put("lat", whCityBean.getLat() + "");
                    jsonObject.put("lng", whCityBean.getLng() + "");
//            if (!TextUtils.isEmpty(whCityBean.getAddressId())) {
//                jsonObject.put("addressId", whCityBean.getAddressId());
//            }
                } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
                    jsonObject.put("whCity", aMapLocation.getProvince() + "," + aMapLocation.getCity());
                    jsonObject.put("lat", aMapLocation.getLatitude() + "");
                    jsonObject.put("lng", aMapLocation.getLongitude() + "");
                }
//                    jsonObject.put("totalAmount", homeDrugEntity.getData().getTotalAmount());
                jsonObject.put("totalQuantity", homeDrugEntity.getData().getTotalQuantity());
//                    jsonObject.put("totalAmount", homeDrugEntity.getData().getTotalAmountStr());
//                    jsonObject.put("totalAmount", String.format("%.2f", totalAmount));
                jsonObject.put("totalAmount", homeDrugEntity.getData().getCheckedTotalAmount());

                JSONArray validateList = new JSONArray();
                JSONArray lisArray = new JSONArray();
                for (DrugEntity entity : selectEntityList) {
                    JSONObject entityJb = new JSONObject();
                    entityJb.put("doctorId", entity.getDoctorId());
                    JSONArray drugArray = new JSONArray();
                    for (DrugEntity.CommodityListBean bean : entity.getCommodityList()) {
                        JSONObject drug = new JSONObject();
                        drug.put("commodityId", bean.getCommodityId());
                        drug.put("commodityType", bean.getCommodityType());
                        drug.put("addedQuantity", bean.getAddedQuantity());
                        drug.put("soldOut", bean.isSoldOut());
                        drug.put("price", bean.getPrice());
                        drugArray.put(drug);
                        validateList.put(drug);
                    }
                    entityJb.put("commodityList", drugArray);
                    lisArray.put(entityJb);
                }

                for (DrugEntity entity : selectO2oEntityList) {
                    for (DrugEntity.CommodityListBean bean : entity.getCommodityList()) {
                        JSONObject drug = new JSONObject();
                        drug.put("commodityId", bean.getCommodityId());
                        drug.put("commodityType", bean.getCommodityType());
                        drug.put("addedQuantity", bean.getAddedQuantity());
                        drug.put("soldOut", bean.isSoldOut());
                        drug.put("price", bean.getPrice());
                        validateList.put(drug);
                    }
                }
                jsonObject.put("list", lisArray);
                validateParams.put("list", validateList);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            LoadingUtils.getLoadingUtils(getActivity()).showLoading();
            HttpUtils.post(cartValidate, validateParams, new HttpCallBack<ValidateEntity>() {
                @Override
                public void onSuccess(ValidateEntity validateEntity, int i) {
                    LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                    if (validateEntity != null) {
                        if (validateEntity.isResult() && validateEntity.isData()) {

                            if (selectO2oEntityList.size() > 0 && selectO2oEntityList.get(0).getCommodityList().size() > 0) {
//                Toast.makeText(getContext(), "O2O 订单页！", Toast.LENGTH_SHORT).show();
                                O2oCartVOSEntity o2oCartVOSEntity = selectO2oEntityList.get(0);
                                Bundle bundle = new Bundle();
                                bundle.putString("doctorId", "" + o2oCartVOSEntity.getCommodityList().get(0).getDoctorId());
                                bundle.putString("storeId", "" + o2oCartVOSEntity.getStoreId());
                                DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
                                AMapLocation aMapLocation = LocationUtils.getInstance().getaMapLocation();
                                if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getAddressId() + "")) {
                                    bundle.putString("addressId", whCityBean.getAddressId());
                                    bundle.putDouble("latitude", whCityBean.getLat());
                                    bundle.putDouble("longitude", whCityBean.getLng());

                                } else if (aMapLocation != null) {
                                    bundle.putDouble("latitude", aMapLocation.getLatitude());
                                    bundle.putDouble("longitude", aMapLocation.getLongitude());
                                }
                                List<ToO2oPayCartDrugEntity> entities = new ArrayList<>();
                                for (DrugEntity.CommodityListBean bean : o2oCartVOSEntity.getCommodityList()) {
                                    ToO2oPayCartDrugEntity entity = new ToO2oPayCartDrugEntity();
                                    entity.setDrugId("" + bean.getDrugId());
                                    entity.setQuantity(Integer.parseInt(bean.getAddedQuantity()));
                                    entities.add(entity);
                                }
                                bundle.putString("drugs", new Gson().toJson(entities));
                                bundle.putString("payChartFlag", "o2o");
//                DrugListUtils.push(getContext(), KitArouterConstants.MY_BUNDLE, PaycartO2o, bundle);
                                DrugListUtils.push(getContext(), KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.PayChart, bundle);

                            } else {
                                carConfirmAdd(jsonObject);
                            }
                        } else {
                            if (!TextUtils.isEmpty(validateEntity.getMsg())) {
                                ToastUtils.showShort(validateEntity.getMsg());
                            }
                        }
                    }

                }

                @Override
                public void onFailure(String s, int i) {
                    LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                    try {
                        ValidateEntity entity1 = new Gson().fromJson(s, ValidateEntity.class);
                        if (!TextUtils.isEmpty(entity1.getMsg())) {
//                            ToastUtils.showShort(entity1.getMsg());

                            if (limitDialog == null && getActivity() != null) {
                                View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_logout_limit_dialog, null);
                                TextView subTv = contentView.findViewById(R.id.tv_sub_title);
                                subTv.setVisibility(View.GONE);
                                TextView contentTv = contentView.findViewById(R.id.content);
                                contentTv.setText(entity1.getMsg());
                                TextView titleTv = contentView.findViewById(R.id.title);
                                titleTv.setText("提示");
                                TextView submitTv = contentView.findViewById(R.id.logout);
                                submitTv.setText("确定");
                                submitTv.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        limitDialog.dismiss();
                                    }
                                });
                                limitDialog = new AlertDialog.Builder(getActivity()).show();
                                limitDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                                limitDialog.setContentView(contentView);
//                                        limitDialog.setCancelable(false);
//                                        limitDialog.setCanceledOnTouchOutside(false);
                                limitDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                    @Override
                                    public void onDismiss(DialogInterface dialog1) {
                                        limitDialog = null;
                                        initData();
                                    }
                                });
//                                        return;
                            }

                        }
                    } catch (Throwable throwable) {
                        if (!TextUtils.isEmpty(s)) {
                            ToastUtils.showShort(s);
                        }
                    }
                    initData();
                }
            });
//                LoadingUtils.getLoadingUtils(getActivity()).showLoading();


        } else if (view.getId() == R.id.drug_delete) {
            ClickUtils.sendEvent(ClickApi.CartList.click_btn_delete, getContext(), "删除按钮点击");
            RequestParams jsonObject = new RequestParams();
            JSONArray list = new JSONArray();
            for (int i = 0; i < drugEntityList.size(); i++) {
                JSONObject submitDeleteData = new JSONObject();
                if (drugEntityList.get(i).getCommodityList() != null && drugEntityList.get(i).getCommodityList().size() > 0) {
                    JSONArray jsonArray = new JSONArray();
                    for (int j = 0; j < drugEntityList.get(i).getCommodityList().size(); j++) {
                        if (drugEntityList.get(i).getCommodityList().get(j).isChecked()) {
                            JSONObject data = new JSONObject();
                            try {
                                data.put("addedQuantity", drugEntityList.get(i).getCommodityList().get(j).getAddedQuantity());
                                data.put("commodityId", drugEntityList.get(i).getCommodityList().get(j).getCommodityId());
                                data.put("commodityType", drugEntityList.get(i).getCommodityList().get(j).getCommodityType());
                                data.put("price", drugEntityList.get(i).getCommodityList().get(j).getPrice());
                                jsonArray.put(data);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    if (jsonArray.length() > 0) {
                        try {
                            submitDeleteData.put("doctorId", drugEntityList.get(i).getCommodityList().get(0).getDoctorId() + "");
                            submitDeleteData.put("commodityList", jsonArray);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        list.put(submitDeleteData);
                    }
                }
            }
            if (list.length() == 0) {
//                Toast.makeText(getActivity(), "没有可删除的药品", Toast.LENGTH_SHORT).show();
                ToastUtils.showShort("没有可删除的药品");
                return;
            }
            jsonObject.put("list", list);
            LoadingUtils.getLoadingUtils(getActivity()).showLoading();
            HttpUtils.post(cartDelete, jsonObject, new HttpCallBack<ResultEntity>() {
                @Override
                public void onSuccess(ResultEntity resultEntity, int i) {
                    isShowRefreshLoading = false;
                    if ("200".equals(resultEntity.getCode())) {
                        ToastUtils.showShort("删除成功");
                        initData();
                    } else {
                        initData();
                        if (!TextUtils.isEmpty(resultEntity.getMsg())) {
                            ToastUtils.showShort(resultEntity.getMsg());
                        }
                    }
                }

                @Override
                public void onFailure(String s, int i) {
//                    LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                    ALog.e("chen", s);
                    isShowRefreshLoading = false;
                    initData();
                }
            });
        } else if (view.getId() == R.id.drug_all_choice) {
            ClickUtils.sendEvent(ClickApi.CartList.click_all_choice, getContext(), "药品清单全选");

//            // 医生的问诊开方下的药品和1小时急送药店购买的药品不可以同时选中
//            if (!manageBtnFlag) {
//                boolean hasDrug = false;
//                boolean hasDrugO2O = false;
//                for (DrugEntity entity : drugEntityList) {
//                    if (!hasDrug && entity.getItemType() == ITEM_TYPE_DRUG) {
//                        hasDrug = true;
//                    }
//                    if (!hasDrugO2O && entity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
//                        hasDrugO2O = true;
//                    }
//                }
//                if (hasDrug && hasDrugO2O) {
//                    return;
//                }
//            }


            if (!manageBtnFlag) {
//                if (isAllChoiceFlag) {
//                    isAllChoiceFlag = false;
//                    drug_all_choice.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.uncheck));
//                    setAllChoice(false);
//                } else {
//                    isAllChoiceFlag = true;
//                    drug_all_choice.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.checked));
////                    setAllChoice(true);
//
//
//                    if (selectO2oBeanList.size() > 0) {
////                        totalAmount = 0.0;
//                        selectDrugBeanList.clear();
//                        selectO2oBeanList.clear();
//                        for (int i = 0; i < drugEntityList.size(); i++) {
//                            DrugEntity entity = drugEntityList.get(i);
//                            if (entity.getItemType() == ITEM_TYPE_O2O_CART_VOS) {
//                                for (int j = 0; j < drugEntityList.get(i).getCommodityList().size(); j++) {
//                                    DrugEntity.CommodityListBean bean = entity.getCommodityList().get(j);
//                                    if ("1".equals(bean.getIsRegular())) {
//                                        //定期购商品不可选中
//                                        continue;
//                                    }
//                                    bean.setChecked(true);
////                                    totalAmount += Double.parseDouble(bean.getPrice()) * Integer.parseInt(bean.getAddedQuantity());
//                                    selectO2oBeanList.add(bean);
//                                }
//                                entity.setChoice(true);
//                            }
//                        }
//                    } else if (selectDrugBeanList.size() > 0) {
////                        totalAmount = 0.0;
//                        selectDrugBeanList.clear();
//                        selectO2oBeanList.clear();
//                        for (int i = 0; i < drugEntityList.size(); i++) {
//                            DrugEntity entity = drugEntityList.get(i);
//                            if (entity.getItemType() == ITEM_TYPE_DRUG) {
//                                for (int j = 0; j < drugEntityList.get(i).getCommodityList().size(); j++) {
//                                    DrugEntity.CommodityListBean bean = entity.getCommodityList().get(j);
//                                    if ("1".equals(bean.getIsRegular())) {
//                                        //定期购商品不可选中
//                                        continue;
//                                    }
//                                    bean.setChecked(true);
////                                    totalAmount += Double.parseDouble(bean.getPrice()) * Integer.parseInt(bean.getAddedQuantity());
//                                    selectDrugBeanList.add(bean);
//                                }
//                                entity.setChoice(true);
//                            }
//
//                        }
//                    } else {
////                        totalAmount = 0.0;
//                        for (int i = 0; i < drugEntityList.size(); i++) {
//                            DrugEntity entity = drugEntityList.get(i);
//                            if (selectDrugBeanList.size() > 0 && entity.getItemType() != ITEM_TYPE_DRUG) {
//                                continue;
//                            }
//                            if (selectO2oBeanList.size() > 0 && entity.getItemType() != ITEM_TYPE_O2O_CART_VOS) {
//                                continue;
//                            }
//                            for (int j = 0; j < drugEntityList.get(i).getCommodityList().size(); j++) {
//                                DrugEntity.CommodityListBean bean = entity.getCommodityList().get(j);
//                                if ("1".equals(bean.getIsRegular())) {
//                                    //定期购商品不可选中
//                                    continue;
//                                }
//                                bean.setChecked(true);
////                                totalAmount += Double.parseDouble(bean.getPrice()) * Integer.parseInt(bean.getAddedQuantity());
//                                if (drugEntityList.get(i).getItemType() == ITEM_TYPE_DRUG) {
//                                    selectDrugBeanList.add(bean);
//                                } else if (drugEntityList.get(i).getItemType() == ITEM_TYPE_O2O_CART_VOS) {
//                                    selectO2oBeanList.add(bean);
//                                }
//                            }
//                            entity.setChoice(true);
//                        }
//                    }
//
//
////                    totalAmountTv.setText("¥" + String.format("%.2f", totalAmount));
//                    drugAdapter.notifyDataSetChanged();
//                }
//                if (selectDrugBeanList.size() <= 0 && selectO2oBeanList.size() <= 0) {
//                    reserve.setBackground(getResources().getDrawable(R.drawable.bg_enable_color));
//                } else {
//                    reserve.setBackground(getResources().getDrawable(R.drawable.bg_main_color));
//                }
            } else {
                if (isAllChoiceFlag) {
                    isAllChoiceFlag = false;
                    drug_all_choice.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.uncheck));
                    setAllChoice(false);
                } else {
                    isAllChoiceFlag = true;
                    drug_all_choice.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.checked));
                    setAllChoice(true);
                }
            }


            try {
                if (!manageBtnFlag) {
                    doBatchSave(drugEntityList);
                } else {
                    // 管理编辑购物车状态
                    boolean isHasChecked = false;
                    outer:
                    {
                        for (DrugEntity entity : drugEntityList) {
                            for (DrugEntity.CommodityListBean bean : entity.getCommodityList()) {
                                if (bean.isChecked()) {
                                    isHasChecked = true;
                                    break outer;
                                }
                            }
                        }
                    }
                    if (isHasChecked) {
                        drugDelete.setTextColor(getResources().getColor(R.color.new_theme));
                    } else {
                        drugDelete.setTextColor(getResources().getColor(R.color.color_b3));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
//        } else if (view.getId() == R.id.chooseAddress) {
//            Bundle bundle = new Bundle();
//            bundle.putString("tag", "choose");
//            bundle.putString("pushTag", "fromNativeDrugList");
//            bundle.putBoolean("isO2O", isHasO2oDrugs);
//            DrugListUtils.push(getActivity(), KitArouterConstants.MY_BUNDLE, KitArouterConstants.MyAddress, bundle);
        } else if (view.getId() == R.id.address_layout) {
            ClickUtils.sendEvent(ClickApi.CartList.click_select_address, getContext(), "选择地址点击");

            Bundle bundle = new Bundle();
            bundle.putString("tag", "choose");
            bundle.putString("pushTag", "fromNativeDrugList");
            bundle.putBoolean("isO2O", isHasO2oDrugs);
            DrugListUtils.push(getActivity(), KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyAddress, bundle);
        }
    }

    private void carConfirmAdd(RequestParams jsonObject) {
        LoadingUtils.getLoadingUtils(getActivity()).showLoading();
        HttpUtils.post(carConfirmAdd, jsonObject, new HttpCallBack<CartConfirmAddEntity>() {
            @Override
            public void onSuccess(CartConfirmAddEntity resultEntity, int i) {
                if (resultEntity.getStatus().equals("200")) {
                    Bundle bundle = new Bundle();
                    if (isOpenGroup && "3".equals(resultEntity.getData().getDispatch())) {
                        bundle.putString("confirmId", resultEntity.getData().getConfirmId());
                        bundle.putString("dispatch", resultEntity.getData().getDispatch());
                        DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
                        AMapLocation aMapLocation = LocationUtils.getInstance().getaMapLocation();
                        if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
                            bundle.putString("address", new Gson().toJson(whCityBean));
                        } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
                            bundle.putString("address", new Gson().toJson(aMapLocation));
                        }
                        DrugListUtils.push(getActivity(), KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.Inquiry1, bundle);
                    } else {
                        bundle.putString("id", resultEntity.getData().getConfirmId());
                        bundle.putString("dispatch", resultEntity.getData().getDispatch());
                        DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
                        AMapLocation aMapLocation = LocationUtils.getInstance().getaMapLocation();
                        if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
                            bundle.putString("address", new Gson().toJson(whCityBean));
                        } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
                            bundle.putString("address", new Gson().toJson(aMapLocation));
                        }
                        DrugListUtils.push(getActivity(), KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.PayChart, bundle);
                    }
                } else {
                    if ("InventoryShortageException".equals(resultEntity.getStatus())) {
//                                    Toast.makeText(getContext(), "您购买的部分商品暂时无货或库存不足，返回药品清单修改", Toast.LENGTH_SHORT).show();
                        ToastUtils.showShort("您购买的部分商品暂时无货或库存不足，返回药品清单修改");
                        initData();
                    } else if ("PrescriptionTypeException".equals(resultEntity.getStatus())) {
//                                    Toast.makeText(getContext(), "您所选处方药种类超过5种，请重新选择后预定。", Toast.LENGTH_SHORT).show();
                        if (limitDialog == null && getActivity() != null) {
                            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_logout_limit_dialog, null);
                            TextView subTv = contentView.findViewById(R.id.tv_sub_title);
                            SpannableString spannableString = new SpannableString(subTv.getText().toString());
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                                spannableString.setSpan(new TypefaceSpan(DEFAULT_BOLD), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }
                            subTv.setText(spannableString);
                            contentView.findViewById(R.id.logout).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    limitDialog.dismiss();
                                }
                            });
                            limitDialog = new AlertDialog.Builder(getActivity()).show();
                            limitDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                            limitDialog.setContentView(contentView);
//                                        limitDialog.setCancelable(false);
//                                        limitDialog.setCanceledOnTouchOutside(false);
                            limitDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog1) {
                                    limitDialog = null;
                                    initData();
                                }
                            });
//                                        return;
                        } else {
                            initData();
                        }
                    } else if (!TextUtils.isEmpty(resultEntity.getMessage())) {
//                                    Toast.makeText(getContext(), resultEntity.getMessage(), Toast.LENGTH_SHORT).show();
//                                    initData();
                        if (limitDialog == null && getActivity() != null) {
                            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_logout_limit_dialog, null);
                            TextView subTv = contentView.findViewById(R.id.tv_sub_title);
                            subTv.setVisibility(View.GONE);
                            TextView titleTv = contentView.findViewById(R.id.title);
                            TextView contentTv = contentView.findViewById(R.id.content);
                            TextView logout = contentView.findViewById(R.id.logout);
                            titleTv.setText("提示");
                            logout.setText("确定");
                            contentTv.setText(resultEntity.getMessage());
                            contentTv.setGravity(View.TEXT_ALIGNMENT_CENTER);
                            logout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    limitDialog.dismiss();
                                }
                            });
                            limitDialog = new AlertDialog.Builder(getActivity()).show();
                            limitDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                            limitDialog.setContentView(contentView);
//                                        limitDialog.setCancelable(false);
//                                        limitDialog.setCanceledOnTouchOutside(false);
                            limitDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog1) {
                                    limitDialog = null;
                                    initData();
                                }
                            });
//                                        return;
                        } else {
                            initData();
                        }
                    }
                }
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
                initData();
            }
        });
    }

    //控制全选逻辑
    void setAllChoice(boolean isAllChoiceFlag) {
//        totalAmount = 0.0;
        selectDrugBeanList.clear();
        selectO2oBeanList.clear();
        for (int i = 0; i < drugEntityList.size(); i++) {
            for (int j = 0; j < drugEntityList.get(i).getCommodityList().size(); j++) {
                DrugEntity.CommodityListBean bean = drugEntityList.get(i).getCommodityList().get(j);
                bean.setChecked(isAllChoiceFlag);
                if (isAllChoiceFlag) {
//                    totalAmount += Double.parseDouble(bean.getPrice()) * Integer.parseInt(bean.getAddedQuantity());
                }
                if (isAllChoiceFlag) {
                    if (!manageBtnFlag) {
                        if (drugEntityList.get(i).getItemType() == ITEM_TYPE_DRUG) {
                            selectDrugBeanList.add(bean);
                        } else if (drugEntityList.get(i).getItemType() == ITEM_TYPE_O2O_CART_VOS) {
                            selectO2oBeanList.add(bean);
                        }
                    }
//                } else {
//                    if (!manageBtnFlag) {
//                        if (drugEntityList.get(i).getItemType() == ITEM_TYPE_DRUG) {
//                            selectDrugBeanList.clear();
//                        } else if (drugEntityList.get(i).getItemType() == ITEM_TYPE_O2O_CART_VOS) {
//                            selectO2oBeanList.clear();
//                        }
//                    }
                }

            }

            drugEntityList.get(i).setChoice(isAllChoiceFlag);
        }
//        totalAmountTv.setText("¥" + String.format("%.2f", totalAmount));
        drugAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消注册事件
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        PermissionManager.getInstance()
                .get(getContext())
                .requestPermissions(
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}
                        ,
                        new String[]{"允许应用使用位置权限"})
                .requestCodes(0xa1)
                .setmRequestPermissionCallBack(new PermissionManager.RequestPermissionCallBack() {
                    @Override
                    public void noM() {

                    }

                    @Override
                    public void granted() {
                        HttpUtils.cancel(cartList);
                        initData();
                    }

                    @Override
                    public void denied() {
//                        ToastUtils.make().setBgColor(getContext().getResources().getColor(R.color.color_99000000))
//                                .setTextColor(getContext().getResources().getColor(R.color.white))
//                                .show("请到权限管理打开位置权限/GPS定位");
                    }
                })
                .request();


//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("name", "药品清单显示");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        ClickUtils.sendEvent("pages_cart_show", getContext(), jsonObject);
        ClickUtils.sendEvent(ClickApi.CartList.page_show, getContext(), "药品清单载入");

//        LoadingUtils.getLoadingUtils(getActivity()).showLoading();
        DrugListBackApi api = (DrugListBackApi) ARouter.getInstance().build(DrugListModuleImpl).navigation();
        HashMap<String, String> map = api.getTemporaryDataStorage();
        if (!TextUtils.isEmpty(map.get("addressInfo"))) {
            ALog.e("drugAdress", "drug address info: " + map.get("addressInfo"));
            DefaultEntity.DataBean whCityBean = new Gson().fromJson(map.get("addressInfo"), DefaultEntity.DataBean.class);
            LocationUtils.getInstance().setWhCityBean(whCityBean);
            addressTv.setText(whCityBean.getDetailAddress());
//            map.put("addressInfo", "");
        } else {
            LocationUtils.getInstance().setWhCityBean(null);
            addressTv.setText("");
        }
        initData();
        super.onResume();
        contentFl.getViewTreeObserver().addOnGlobalLayoutListener(contentLayoutListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        contentFl.getViewTreeObserver().removeOnGlobalLayoutListener(contentLayoutListener);
    }
}
